package org.example.jwt.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.example.jwt.bean.User;
import org.example.jwt.config.JwtConfig;
import org.example.jwt.util.JsonResult;
import org.example.jwt.util.ResultTool;
import org.example.jwt.mapper.UserMapper;
import org.example.jwt.service.UserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper mapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
@Override
    public JsonResult login(User user) {
        // 首先判断账号密码是否正确
        User result = mapper.login(user);
        if (result == null) {
            return ResultTool.fail(501, "账号或者密码错误");
        }
        // 和过去不一样了 过去是将用户保存到session中
        // 1. 生成jwt字符串
        String token = JwtConfig.getJwtToken(result);
        // 2. 保存到redis中
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set("token:"+result.getId(), token);
        // 3. 返回给用户jwt字符串
        return ResultTool.success(token);
    }
}
